package com.hzsparrow.business.base.config;

import com.hzsparrow.business.base.config.shiro.HzsparrowShiroFormAuthenticationFilter;
import com.hzsparrow.business.base.config.shiro.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.PostConstruct;

@Configuration
public class ShiroConfig {

    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    @PostConstruct
    protected void initHzsparrowShiroFilter() {
        shiroFilterFactoryBean.getFilters().put("authc", new HzsparrowShiroFormAuthenticationFilter());
    }

    @Bean("authorizer")
    public UserRealm userRealm() {
        return new UserRealm();
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/hzs/login", "anon");
        chainDefinition.addPathDefinition("/hzs/logout", "anon");
        chainDefinition.addPathDefinition("/hzs/getVerifyCode", "anon");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }

    @Bean
    @DependsOn({"lifecycleBeanPostProcessor"})
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }
}
